package io.renren.modules.dataInitialization.service.impl;

import io.renren.modules.dataInitialization.dao.BinzhiCourseInfoDao;
import io.renren.modules.dataInitialization.entity.BinzhiCourseInfoEntity;
import io.renren.modules.dataInitialization.service.BinzhiCourseInfoService;
import io.renren.modules.jxgk.entity.ClassCourse2Entity;
import io.renren.modules.jxgk.service.ClassCourse2Service;
import io.renren.modules.jxgk.service.WebSocket;
import io.renren.modules.jxgkphone.entity.DateInfo;
import io.renren.modules.jxgkphone.service.ClassCourseService;
import io.renren.modules.pullin.DataConversion.TeachControlView;

import io.renren.modules.pullin.entity.ClassCourse;
import io.renren.modules.pullin.service.PullOutService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class BinzhiCourseInfoServiceImpl implements BinzhiCourseInfoService{
    @Autowired
    BinzhiCourseInfoDao binzhiCourseInfoDao;
    @Autowired
    ClassCourse2Service classCourse2Service;
    @Autowired
    WebSocket webSocket;
    @Autowired
    ClassCourseService classCourseService;
    @Autowired
    PullOutService pullOutService;
    private int datacounter=0;
    public BinzhiCourseInfoEntity queryUnique(String className,
                                       String courseId){
        return  binzhiCourseInfoDao.queryUnique(className,courseId);
    }
    public void deleteUnique(String className, String courseId){
        binzhiCourseInfoDao.deleteUnique(className,courseId);
        pullOutService.DeleteClassCourseByClassNameAndCourseId(className,courseId);
    }
    public List<BinzhiCourseInfoEntity> queryList(Map<String, Object> map){
        return binzhiCourseInfoDao.queryList(map);
    }
    public int queryTotal(Map<String, Object> map){
        return  binzhiCourseInfoDao.queryTotal(map);
    }
    public void deleteBatch(String[] termIds){
        binzhiCourseInfoDao.deleteBatch(termIds);
    }
    public void save(BinzhiCourseInfoEntity ste,String year,String term){
        binzhiCourseInfoDao.save(ste);
        dataConverter(ste,year,term,1,1);
    }
    public BinzhiCourseInfoEntity queryObject(String index){
        return binzhiCourseInfoDao.queryObject(index);
    }
    public void update(BinzhiCourseInfoEntity ste,String year,String term){
        binzhiCourseInfoDao.update(ste);
        dataConverter(ste,year,term,1,1);
    }
    public void insertIntoDataBase(InputStream inputStream, String year, String term){
        //文件转实体数据
        List<BinzhiCourseInfoEntity> BinzhiCourseInfoEntitys= excelToEntity(inputStream);
        //实体数据插入课程信息表
        insertIntoCourseInfo(BinzhiCourseInfoEntitys);
        //实体数据插入课程表
       insertInToClassCourse(BinzhiCourseInfoEntitys,year,term);
    }
    private void insertIntoCourseInfo(List<BinzhiCourseInfoEntity> BinzhiCourseInfoEntity){
        for(BinzhiCourseInfoEntity b:BinzhiCourseInfoEntity){
            String className=b.getClassName();
            String courseId=b.getCourseId();
            if(className!=null&&courseId!=null){

                BinzhiCourseInfoEntity exist=binzhiCourseInfoDao.queryUnique(className,courseId);
                //如果已有，删除
                if(exist!=null){
                    binzhiCourseInfoDao.deleteUnique(className,courseId);
                }
                binzhiCourseInfoDao.save(b);
            }
        }
    }
    private void dataConverter(BinzhiCourseInfoEntity t,String year,String term,double k,double size){
        //收集错误信息
        String errReason;
        String errId;
        String errPos;
        String errResult;
        //数据结构转换
        TeachControlView tcv=new TeachControlView();
        List<ClassCourse> exist=pullOutService.findClassCourseByClassNameAndCourseId(t.getClassName(),t.getCourseId());
        //如果存在，删除
        if(!exist.isEmpty()){
            pullOutService.DeleteClassCourseByClassNameAndCourseId(t.getClassName(),t.getCourseId());
            System.out.println("log:数据重复,删除");
        }
        //上课时间为空，数据有误
        if(t.getClassTime()!=null){
            try {
                //数据格式转换
                List<ClassCourse> l=tcv.InformationSet(t.getCourseId(),t.getCourseName(),t.getClassName(),t.getTeacherName(),
                        t.getTeacherId(),term,year,t.getClassLocation(),t.getClassTime(),t.getStudentCollege());
                double i=1;
                for(ClassCourse c:l){
                    String courseTime=SetCourseTime(c);
                    c.setCourse_time(courseTime);
                    pullOutService.insertClassCourse(c);
                    System.out.println("log:插入数据成功，本条第"+datacounter+"条");

                    double percentage=k+i*100/(l.size()*size);
                    //保留两位小数
                    BigDecimal b = new BigDecimal(percentage);
                    double df = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    webSocket.sendMessage(""+df);
                    datacounter++;
                    i++;
                }
            }
            catch (Exception e){
                errReason="\n班级课程信息错误原因:"+e+"\n";
                errId="错误位置:"+datacounter+"\n";
                errPos="错误信息:"+t.getCourseId()+"\n";
                errResult=errReason+errId+errPos;
                tcv.appendMethodB("errInfo.txt",errResult);
            }
    }
    }
    private void insertInToClassCourse(List<BinzhiCourseInfoEntity> BinzhiCourseInfoEntitys,String year,String term){
        double k=0;
        double size=BinzhiCourseInfoEntitys.size();
        for(BinzhiCourseInfoEntity t:BinzhiCourseInfoEntitys){
            double percentage=k/size*100;
            dataConverter(t,year,term,percentage,size);
            k++;
        }
        //上传成功 清零
        datacounter=0;
    }
    private List<BinzhiCourseInfoEntity> excelToEntity(InputStream inputStream) {
        List<BinzhiCourseInfoEntity> classCourses=new ArrayList<>();
        HSSFWorkbook wb = null;
        //保存文件信息
        try {
            wb = new HSSFWorkbook(inputStream);
            // logger.debug(wb.getNumberOfSheets());
            HSSFSheet sheet = wb.getSheetAt(0);
            //直接把表头直接加上了，如果数据没错乱的话，可以直接导入。
            int firstRound=1;
            int position[]=new int[8];
            for(int i = sheet.getFirstRowNum();i<=sheet.getLastRowNum();i++){
                HSSFRow row = sheet.getRow(i);
                Iterator cells = row.cellIterator();
                //大脑有点当机，想不出更好点的办法了，先这样吧，用循环赋值
                BinzhiCourseInfoEntity temp=new BinzhiCourseInfoEntity();
                classCourses.add(temp);
                int j=1;


                //初始化数据在Excel中的位置
                while (cells.hasNext()&&firstRound==1){
                    HSSFCell cell = (HSSFCell) cells.next();
                    String s=cell.toString();
                    if(s.equals("班级名称"))
                        position[0]=j;
                    if(s.equals("教师姓名"))
                        position[1]=j;
                    if(s.equals("课程名称"))
                        position[2]=j;
                    if(s.equals("教师职工号"))
                        position[3]=j;
                    if(s.equals("上课地点"))
                        position[4]=j;
                    if(s.equals("上课时间"))
                        position[5]=j;
                    if(s.equals("选课课号"))
                        position[6]=j;
                    if(s.equals("学生学院"))
                        position[7]=j;
                    j++;
                }
                firstRound=2;
                while(cells.hasNext()&&firstRound!=1){
                    HSSFCell cell = (HSSFCell) cells.next();
                    String s=cell.toString();
                    if(j==position[0])
                        temp.setClassName(s);
                    if(j==position[1])
                        temp.setTeacherName(s);
                    if(j==position[2])
                        temp.setCourseName(s);
                    if(j==position[3])
                        temp.setTeacherId(s);
                    if(j==position[4])
                        temp.setClassLocation(s);
                    if(j==position[5])
                        temp.setClassTime(s);
                    if(j==position[6])
                        temp.setCourseId(s);
                    if(j==position[7])
                        temp.setStudentCollege(s);
                    j++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return classCourses;
    }
    @RequestMapping("/AddTimeLabel")
    public void AddTimeLabel(){
        String date;
        String time="";
        String courseTime;
        int i=1;
        List<ClassCourse2Entity> classCourse2EntityList=classCourse2Service.selectAll();
        for(ClassCourse2Entity temp:classCourse2EntityList){
            if(temp.getCourseWhichIndex().equals("1"))
                time="08:00:00";
            if(temp.getCourseWhichIndex().equals("3"))
                time="10:00:00";
            if(temp.getCourseWhichIndex().equals("5"))
                time="13:30:00";
            if(temp.getCourseWhichIndex().equals("7"))
                time="15:30:00";
            if(temp.getCourseWhichIndex().equals("9"))
                time="18:30:00";
            DateInfo dateInfo=new DateInfo();
            dateInfo.setCourseAcademicYear(temp.getCourseAcademicYear());
            dateInfo.setCourseAcademicTerm(temp.getCourseAcademicTerm());
            dateInfo.setCourseWhichWeek(temp.getCourseWhichWeek());
            dateInfo.setCourseWhichDay(temp.getCourseWhichDay());
            date=classCourseService.findDateByDateInfo(dateInfo);
            courseTime=date+" "+time;
            //填写到数据库
            classCourse2Service.updateCourseTime(courseTime,temp.getClassCourseId());
            System.out.println("更新数据完成，第"+i+"条");
            i++;
        }

    }
    public String SetCourseTime(ClassCourse classCourse){
        String date;
        String time="";
        String courseTime;
        if(classCourse.getCourse_which_index().equals("1"))
            time="08:00:00";
        if(classCourse.getCourse_which_index().equals("3"))
            time="10:00:00";
        if(classCourse.getCourse_which_index().equals("5"))
            time="13:30:00";
        if(classCourse.getCourse_which_index().equals("7"))
            time="15:30:00";
        if(classCourse.getCourse_which_index().equals("9"))
            time="18:30:00";
        DateInfo dateInfo=new DateInfo();
        dateInfo.setCourseAcademicYear(classCourse.getCourse_academic_year());
        dateInfo.setCourseAcademicTerm(classCourse.getCourse_academic_term());
        dateInfo.setCourseWhichWeek(classCourse.getCourse_which_week());
        dateInfo.setCourseWhichDay(classCourse.getCourse_which_day());
        date=classCourseService.findDateByDateInfo(dateInfo);
        courseTime=date+" "+time;
        return  courseTime;
    }
}
